<?php
namespace Amoysea\Controller;
use Think\Controller;
//外部接口
class ApiController extends Controller {
    public function _initialize(){

    }
	//推送云仓库存
	//$type--insert--edit--delete
	public function push_yungoods($id,$type){
		$username=session('company.username');
        $ao=M('ArrivalOrder',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);
		
		if($type=="delete"){
			$map_ao['id']=array('in',$id);
			$ao_list=$ao->field('goods_no goods_sn')->where($map_ao)->select();
		}else{
			$map_ao['id']=$id;
			$ao_list=$ao->field('goods_name,price goods_price,receive_amount goods_number,goods_no goods_sn,source_no goods_pn,net_weight,gross_weight,3 is_cross,goods_tax g_tax')->where($map_ao)->find();
		}
		

		// echo $ao->getlastsql();
		$url=C('BASE_CONFIG.yuncang_goods');//云仓同步添加商品接口
		$token=C('BASE_CONFIG.yuncang_token');//云仓同步添加商品接口
		$push_list['warehouse_code']=session('company.warehouse_code');
		$push_list['token']=$token;
		$push_list['type']=$type;
		$push_list['data'][0]=$ao_list;
		// var_dump($push_list);
		$res = push($url,$push_list);
		if(!$res['status']){	//失败
			$return['status']=0;
			$return['message']='推送云仓数据失败，请重新推送';
			$this->ajaxReturn($return);
		}else{
			$ao->where($map_ao)->setField('push_yuncang_status',1);//更新推送状态
			$return['message']='添加成功!';
			$return['status']=true; 
			$this->ajaxReturn($return);
		}
    }
	//库存更新(按批次)
	//status:1-冻结2-出库3-退库4-入库
	public function update_goodsamount(){
		$data=file_get_contents("php://input");
		// file_put_contents('./log/update_goodsamount.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		// die;
        $param=json_decode($data,true);
		if(!isset($data) || count($data)==0){
            $return['status']=false;
			$return['message']='操作有误';
			$this->ajaxReturn($return);
        }
		$warehouse_code=$param['warehouse_code'];
		$erp_code=$param['erp_code'];
		$status=$param['status'];
		$amount=$param['amount'];
		$id=$param['id'];
		$cloud_status=$param['cloud_status'];//是否云仓商品
		if(empty($id)){
			$return['status']=0;
			$return['info']="没有传输入库批次id";
			$this->ajaxReturn($return);
		}
		if(empty($erp_code)){
			$return['status']=0;
			$return['info']="没有传输企业编码";
			$this->ajaxReturn($return);
		}
		if(empty($warehouse_code)){
			$return['status']=0;
			$return['info']="没有传输仓库编码";
			$this->ajaxReturn($return);
		}
		if(empty($status)){
			$return['status']=0;
			$return['info']="没有传输更新状态参数";
			$this->ajaxReturn($return);
		}
		if(empty($amount)){
			$return['status']=0;
			$return['info']="没有传输数量";
			$this->ajaxReturn($return);
		}
		$username=M('user')->where("id=".$erp_code)->getField('username');
        $ao=M('ArrivalOrder',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);

		if($status==1){//当前操作为冻结状态
			$data_ao['freez_amount']=array('exp','freez_amount+'.$amount);//冻结数量
			$data_ao['storage_amount']=array('exp','storage_amount-'.$amount);//更新库存
			if(empty($cloud_status)){
				$data_ao['cloud_freez_num']=array('exp','cloud_freez_num+'.$amount);//冻结云仓数量
				$data_ao['cloud_storage_num']=array('exp','cloud_storage_num-'.$amount);//更新云仓库存
			}
		}
		if($status==2){//当前操作为出库状态
			$data_ao['freez_amount']=array('exp','freez_amount-'.$amount);//冻结数量
			if(empty($cloud_status)){
				$data_ao['cloud_freez_num']=array('exp','cloud_freez_num-'.$amount);//冻结数量
			}
		}
		if($status==3){//当前操作为退库状态
			$data_ao['freez_amount']=array('exp','freez_amount-'.$amount);//冻结数量
			$data_ao['storage_amount']=array('exp','storage_amount+'.$amount);//更新库存
			if(empty($cloud_status)){
				$data_ao['cloud_freez_num']=array('exp','cloud_freez_num-'.$amount);//冻结数量
				$data_ao['cloud_storage_num']=array('exp','cloud_storage_num+'.$amount);//更新库存
			}
		}
		// if($status==4){//当前操作为入库状态（仓库入库，erp要同步插入批次数据）
			
		// }
		$map_ao['id']=$id;//条件
		$map_ao['id']=$id;//条件
		$res_ao=$ao->where($map_ao)->save($data_ao);//更新
		if($res_ao){
			$return['status']=1;
			$return['info']="更新成功";
			$this->ajaxReturn($return);
		}else{
			$return['status']=0;
			$return['info']="更新批次库存失败";
			$this->ajaxReturn($return);
		}
	}
	//批次库存同步（仓库入库-erp则同步仓库批次入库信息）
	public function inbound_batch(){
		$data=file_get_contents("php://input");
		// file_put_contents('./log/inbound_batch.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		// die;
        $param=json_decode($data,true);
		$return=array();
		if(!isset($param) || count($param)==0){
            $return['status']=false;
			$return['message']='操作有误';
			$this->ajaxReturn($return);
        }
		$data_ao['warehouse_code']=$param['warehouse_code'];
		$data_ao['goods_no']=$param['goods_no'];
		$data_ao['manual_id']=$param['manua_id'];
		$data_ao['batch_no']=$param['batch_no'];

		$data_ao['goods_sn']=trim($param['goods_no']).$param['warehouse_code'];//货号
		$data_ao['grounding_status']=0;
		
		$data_ao['old_arrival_id']=$param['id'];

		$data_ao['old_goods_id']=$param['old_goods_id'];
		$data_ao['overdue_time']=$param['overdue_time'];
		$data_ao['declare_unit']=$param['declare_unit'];
		$data_ao['unit1']=$param['unit1'];
		$data_ao['unit2']=$param['unit2'];
		$data_ao['goods_spec']=$param['goods_spec'];
		$data_ao['goods_cate']=$param['goods_cate'];
		$data_ao['storage_id']=$param['storage_id'];
		$data_ao['cloud_depot_status']=$param['cloud_depot_status'];
		$data_ao['cloud_num']=$param['cloud_num'];
		$data_ao['cloud_unit']=$param['cloud_unit'];
		$data_ao['add_time']=$param['add_time'];
		$data_ao['conforming_p']=$param['conforming_p'];
		$data_ao['nonconforming_p']=$param['nonconforming_p'];
		$data_ao['scrap_one']=$param['scrap_one'];
		$data_ao['scrap_two']=$param['scrap_two'];
		$data_ao['bar_code']=$param['bar_code'];
		$data_ao['currency']=$param['currency'];
		$data_ao['country_code']=$param['country_code'];
		$data_ao['price']=$param['price'];
		$data_ao['total_price']=$param['total_price'];
		$data_ao['amount']=$param['receive_amount'];
		$data_ao['receive_amount']=$param['receive_amount'];
		$data_ao['declare_amount']=$param['declare_amount'];
		$data_ao['storage_amount']=$param['storage_amount'];
		$data_ao['freez_amount']=$param['freez_amount'];
		
		$data_ao['goods_name']=$param['goods_name'];
		$data_ao['item_type']=$param['item_type'];
		$data_ao['item_no']=$param['item_no'];
		$data_ao['source_no']=$param['source_no'];
		
		$username=M('user')->where("id=".$param['erp_code'])->getField('username');
        $ao=M('ArrivalOrder',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);
		$res=$ao->add($data_ao);
		if($res){
			$return['status']=false;
			$return['message']='添加成功';
			$this->ajaxReturn($return);
		}
		
	}
	///库存同步--接收wms推送过来的商品库存信息
    public function receive_synch_goods(){
        $data=file_get_contents("php://input");
		// file_put_contents('./log/receive_synch_goods.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		// die;
        $data=json_decode($data,true);
		// dump($data);
		$return=array();
        if(!isset($data) || count($data)==0){
            $return['status']=false;
			$return['message']='操作有误';
			alert(0,$return);
        }
        
        $k=0;
        foreach($data as $k=>$v){
            $username=M('user')->where("id=".$v['erp_code'])->getField('username');
            $ao=M('ArrivalOrder',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);
            $where['warehouse_code']=$v['warehouse_code'];
			$where['goods_no']=$v['goods_no'];
			$where['manua_id']=$v['manua_id'];
			foreach($v['goods_info_list'] as $ks=>$vs){//商品批次列表
				$where['batch_no']=$vs['batch_no'];
				$ao_info=$ao->where($where)->find();
				//要添加(更新的信息)
				
				$data_ao['warehouse_code']=$v['warehouse_code'];
				$data_ao['goods_sn']=trim($v['goods_no']).$v['warehouse_code'];//货号
				$data_ao['grounding_status']=0;
				
				$data_ao['old_arrival_id']=$v['id'];
				$data_ao['goods_no']=$v['goods_no'];
				$data_ao['manual_id']=$v['manua_id'];
				$data_ao['batch_no']=$vs['batch_no'];
				$data_ao['old_goods_id']=$vs['old_goods_id'];
				$data_ao['overdue_time']=$vs['overdue_time'];
				$data_ao['declare_unit']=$vs['declare_unit'];
				$data_ao['unit1']=$vs['unit1'];
				$data_ao['unit2']=$vs['unit2'];
				$data_ao['goods_spec']=$vs['goods_spec'];
				$data_ao['goods_cate']=$vs['goods_cate'];
				$data_ao['storage_id']=$vs['storage_id'];
				$data_ao['cloud_depot_status']=$vs['cloud_depot_status'];
				$data_ao['cloud_num']=$vs['cloud_num'];
				$data_ao['cloud_unit']=$vs['cloud_unit'];
				$data_ao['add_time']=$vs['add_time'];
				$data_ao['conforming_p']=$v['conforming_p'];
				$data_ao['nonconforming_p']=$v['nonconforming_p'];
				$data_ao['scrap_one']=$v['scrap_one'];
				$data_ao['scrap_two']=$v['scrap_two'];
				$data_ao['bar_code']=$vs['bar_code'];
				$data_ao['currency']=$vs['currency'];
				$data_ao['country_code']=$vs['country_code'];
				$data_ao['price']=$vs['price'];
				$data_ao['total_price']=$vs['total_price'];
				$data_ao['amount']=$vs['receive_amount'];
				$data_ao['receive_amount']=$vs['receive_amount'];
				$data_ao['declare_amount']=$vs['declare_amount'];
				$data_ao['storage_amount']=$vs['storage_amount'];
				$data_ao['freez_amount']=$vs['freez_amount'];
				
				$data_ao['goods_name']=$vs['goods_name'];
				$data_ao['item_type']=$vs['item_type'];
				$data_ao['item_no']=$vs['item_no'];
				$data_ao['source_no']=$vs['source_no'];
				
				if(empty($ao_info)){//添加（没有此商品库存信息，直接添加）
					$res=$ao->add($data_ao);
					// dump($ao);
					// echo $ao->getlastsql();
					if($res){
						$k++;
						continue;
					}else{
						$return['status']=false;
						$return['message']='成功'.$k.'个,批次号'.$vs['batch_no'].'添加出错';
						alert(0,$return);
					}
				}else{//编辑（没有此商品库存信息，直接覆盖对应字段）
					$res=$ao->where($where)->save($data_ao);
					if($res!==false){
						$k++;
						continue;
					}else{
						$return['status']=false;
						$return['message']='成功'.$k.'个,批次号'.$vs['batch_no'].'更新出错';
						alert(0,$return);
					}
				}
			}
        }
		$return['status']=true;
		$return['message']='全部成功，共'.$k.'个';
		alert(1,$return);
    }
    //////接收实收数据 ///////也需要根据不同的企业编码，将数据推入不同企业，目前只是推一个企业
    public function receivedData(){
        $data=file_get_contents("php://input");
        $data=json_decode($data,true);
        /*$data=array(
            "info" => array(
                0 => array (
                    "old_purchasing_no" => "2017012011776450587660960",
                    "old_goods_id" =>"65",
                    "erp_code" =>  "1",
                    "receive_amount" => "12",
                ),
                 1 => array (
                    "old_purchasing_no" => "2017012011776450587660960",
                    "old_goods_id" =>"66",
                    "erp_code" =>  "1",
                    "receive_amount" => "12",
                )
            ),
            "depot_code" =>"12345",
        );*///测试数据
        if(!isset($data['info']) || count($data['info'])==0){
            alert(0,'操作有误');
        }
        $data=$data['info'];
        $return=array();
        $k=0;
        foreach($data as $k=>$v){
            $username=M('user')->where("id=".$v['erp_code'])->getField('username');
			$where['id']=$v['old_goods_id'];//这里是通过第一个接口发送过去的商品id  是唯一的，所以只需要找到对应数据库就能精确到唯一数据，不需要仓库编码
			
			if($v['bound_cate_code']=="PRO"){
				if($v['primarygoods_status']==1){
					$p=M('ProductOrder',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);
					$true=$p->where($where)->save(array('is_back_count'=>$v['receive_amount'],'is_back'=>1));
				}
				if($v['primarygoods_status']==2){
					$pr=M('ProductOrder',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);
					$p=M('ProductOrderByproduct',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);
					$pr->where($where)->save(array('is_back'=>1));
					$true=$p->where($where)->save(array('is_back_count'=>$v['receive_amount'],'is_back'=>1));
				}
			}else{
				$p=M('list_product',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('DB_PREFIX_T').$username);
				$true=$p->where($where)->save(array('is_back_count'=>$v['receive_amount'],'is_back'=>1));
			}

            if($true){
                $return[$where['id']]['is_true']=$true;
                $return[$where['id']]['erp_code']=$v['erp_code'];
                $k++;
                $this-> massage('实收数据','实收数据回执','采购单中的产品(ID='.$where['id'].')已被回执，回执数量为'.$v['receive_amount'],$username);
            }
        }
        if($k>0){
            alert(1,$return);
        }else{
            alert(0,array());
        }
    }
    public function productExamin(){
        $data=file_get_contents("php://input");
        $data=json_decode($data,true);
        $k=0;
        $where['examined']=1;
        $return=array();
        foreach($data['info'] as $v){
            $username=M("user")->where(array('id'=>$v['erp_code']))->getField('username');
            $this->product=M('product',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' .C('DB_PREFIX_T').$username);
            $where['id']=$v['old_goods_id'];
            $where['zccode']=$v['manua_id'];
            $true=$this->product->where($where)->setField('examined',2);
            if($true){
                $k++;
                $this->massage('产品','产品审核','产品信息(ID='.$where['id'].')已经被审核通过',$username);
                $return[$where['id']]['is_true']=$true;
                $return[$where['id']]['erp_code']=$v['erp_code'];
            }
        }
        if($k>0){
            alert(1,$return);
        }else{
            alert(0,array());
        }
    }
    public function bookExamin(){
        $data=file_get_contents("php://input");
        $data=json_decode($data,true);
        $where['examined']=1;
        $k=0;
        foreach($data['info'] as $d){
            $erp_code=$d['erp_code'];
            $where['book_no']=$d['code'];
            $username=M("user")->where(array('id'=>$erp_code))->getField('username');
            $this->product=M('book',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' .C('DB_PREFIX_T').$username);
            $true=$this->product->where($where)->setField('examined',2);
            if($true){
                $k++;
                $this-> massage('账册','账册审核','账册信息(ID='.$where['id'].')已经被审核通过',$username);
                $return[$where['book_no']]['is_true']=$true;
                $return[$where['book_no']]['erp_code']=$d['erp_code'];
            }
        }
        if($k>0){
            alert(1,$return);
        }else{
            alert(0,array());
        }
    }
    public function massage($type,$title,$detail,$username){
        $massage['url']='';
        $massage['type']=$type;
        $massage['title']=$title;
        $massage['detail']=$detail;
        M('massage',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' .C('DB_PREFIX_T').$username)->add($massage);
    }

    //////////////审核，审核之后 wms返回数量
    public function beforeShelves(){
        $data=file_get_contents("php://input");
        $data=json_decode($data,true);
        $k=0;
        foreach($data as $d){
            $erp_code=$d['erp_code'];
            $username=M("user")->where(array('id'=>$erp_code))->getField('username');
            $where['id']=$d['old_goods_id'];
            $where['is_examined']=0;
            $this->product=M('list_product',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' .C('DB_PREFIX_T').$username);
            $true=$this->product->where($where)->setField('is_examined',1);
            if($true){
                $k++;
                $this-> massage('商品','商品审核','商品信息(ID='.$where['id'].')已经被审核通过',$username);
                $return[$where['id']]['is_true']=$true;
                $return[$where['id']]['erp_code']=$d['erp_code'];
            }
        }
        if($k>0){
            alert(1,$return);
        }else{
            alert(0,array());
        }
    }

    //////////////wms上架（上架之后  ERP可以上架）
    public function beforeShelves_2(){
        $data=file_get_contents("php://input");
        $data=json_decode($data,true);
        $k=0;
		file_put_contents('./log/beforeShelves_2.log',date('Y-m-d H:i:s').var_export($data,true).PHP_EOL,FILE_APPEND);//日志导出sql
       // $data=array (
			  // 0 => 
			  // array (
				// 'old_goods_id' => '130',
				// 'erp_code' => '1',
			  // ),
			// );
        foreach($data as $d){
            $erp_code=$d['erp_code'];
            $username=M("user")->where(array('id'=>$erp_code))->getField('username');
            $where['id']=$d['old_goods_id'];
            // $where['is_shelves']=1;
            $this->product=M('list_product',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' .C('DB_PREFIX_T').$username);
			
            $true=$this->product->where($where)->setField('is_shelves',2);
            if($true){
                $k++;
                $this-> massage('商品','商品审核','商品信息(ID='.$where['id'].')已经被审核通过',$username);
                $return[$where['id']]['is_true']=$true;
                $return[$where['id']]['erp_code']=$d['erp_code'];
            }
        }
        if($k>0){
            alert(1,$return);
        }else{
            alert(0,array());
        }
    }
}